package com.mmall.filter;

import com.google.common.collect.Sets;
import com.mmall.common.ApplicationContextHelper;
import com.mmall.common.RequestHolder;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.SysUser;
import com.mmall.service.ISysCoreService;
import com.mmall.service.impl.SysCoreServiceImpl;
import com.mmall.util.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @Author wangtengyu
 * @Create 2018-03-19-15:53
 */
public class AuthFilter implements Filter {

    private static Set<String> exclusionUrlSet=Sets.newHashSet();

    private String noAuthUrl="/sys/user/noAuth.page";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String exclusionUrls=filterConfig.getInitParameter("exclusionUrls");
        if(exclusionUrls.length()>0){
            String[] exclusionUrlsArray=exclusionUrls.split(",");
            List<String> exclusionUrlsList=Arrays.asList(exclusionUrlsArray);
            exclusionUrlSet= Sets.newHashSet(exclusionUrlsList);
            exclusionUrlSet.add(noAuthUrl);
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String servletPath=request.getServletPath();

        //配置的非拦截页面
        if(exclusionUrlSet.contains(servletPath)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        SysUser user= RequestHolder.getCurrentUser();
        if(user==null){
            noAuth(request,response);
            return;
        }

        ISysCoreService iSysCoreService= ApplicationContextHelper.getBean(SysCoreServiceImpl.class);
        if (!iSysCoreService.hasUrlAcl(servletPath)) {
            noAuth(request, response);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
        return;





    }


    private void noAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String servletPath = request.getServletPath();
        if (servletPath.endsWith(".json")) {
            ServerResponse serverResponse=ServerResponse.createByErrorMessage("没有访问权限，如需要访问，请联系管理员");
            response.setHeader("Content-Type", "application/json");
            response.getWriter().print(JsonUtil.obj2String(serverResponse));
            return;
        } else {
            clientRedirect(noAuthUrl, response);
            return;
        }
    }

    private void clientRedirect(String url, HttpServletResponse response) throws IOException{
        response.setHeader("Content-Type", "text/html");
        response.getWriter().print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
                + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n"
                + "<title>跳转中...</title>\n" + "</head>\n" + "<body>\n" + "跳转中，请稍候...\n" + "<script type=\"text/javascript\">//<![CDATA[\n"
                + "window.location.href='" + url + "?ret='+encodeURIComponent(window.location.href);\n" + "//]]></script>\n" + "</body>\n" + "</html>\n");
    }

    @Override
    public void destroy() {

    }
}
